package com.crocodileQ.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crocodileQ.common.R;
import com.crocodileQ.constants.SystemConstants;
import com.crocodileQ.domain.VO.CategoryVO;
import com.crocodileQ.domain.entity.Article;
import com.crocodileQ.domain.entity.Category;
import com.crocodileQ.mapper.CategoryMapper;
import com.crocodileQ.service.ArticleService;
import com.crocodileQ.service.CategoryService;
import com.crocodileQ.utils.BeanCopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**f
 * (Category)表服务实现类
 *
 * @author makejava
 * @since 2023-12-31 21:38:45
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    @Autowired
    private ArticleService articleService;

    /**
     * 所有文章分类查询
     * @return
     */
    public R<List<CategoryVO>> getCategoryList() {
        //查询文章表，状态为已发布的文章
        LambdaQueryWrapper<Article> articleQuery = new LambdaQueryWrapper<>();
        articleQuery.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articleList = articleService.list(articleQuery);

        //获取文章的分类id，并去重
        Set<Long> categoryIds = articleList.stream()
                .map(Article::getCategoryId)
                .collect(Collectors.toSet());

        //查询分类表
        List<Category> categories = listByIds(categoryIds);

        categories = categories.stream()
                .filter(category -> SystemConstants.CATEGORY_STATUS_NORMAL.equals(category.getStatus()))
                .collect(Collectors.toList());

        //封装vo
        List<CategoryVO> categoryVOS = BeanCopyUtil.copyBeanList(categories, CategoryVO.class);

        return R.success(categoryVOS);
    }
}

